import json
import grpc
import consul
from inventory_srv.proto import inventory_pb2_grpc, inventory_pb2
from inventory_srv.settings import settings
from google.protobuf import empty_pb2


class InventoryTest:
    def __init__(self):
        # 连接grpc服务器
        c = consul.Consul(host="192.168.10.130", port=8500)
        services = c.agent.services()
        ip = ""
        port = ""
        for key, value in services.items():
            if value["Service"] == settings.SERVICE_NAME:
                ip = value["Address"]
                port = value["Port"]
                break
        if not ip:
            raise Exception()

        channel = grpc.insecure_channel(f"{ip}:{port}")
        self.inventory_stub = inventory_pb2_grpc.InventoryStub(channel)

    def set_inv(self):
        rsp: empty_pb2.Empty = self.inventory_stub.SetInv(
            inventory_pb2.GoodsInvInfo(goodsId=10, num=100)
        )
        print(rsp)

    def sell(self):
        goods_list = [(1, 3), (3, 5)]
        request = inventory_pb2.SellInfo()
        for goods_id, num in goods_list:
            request.goodsInfo.append(inventory_pb2.GoodsInvInfo(goodsId=goods_id, num=num))
        rsp: empty_pb2.Empty = self.inventory_stub.Sell(
            request
        )
        print(rsp)

    def reback(self):
        goods_list = [(1, 3), (30, 100)]
        request = inventory_pb2.SellInfo()
        for goods_id, num in goods_list:
            request.goodsInfo.append(inventory_pb2.GoodsInvInfo(goodsId=goods_id, num=num))
        rsp: empty_pb2.Empty = self.inventory_stub.Reback(
            request
        )
        print(rsp)


if __name__ == '__main__':
    inv = InventoryTest()
    # goods.goods_list()
    # goods.batch_get()
    # goods.get_detail(421)
    # goods.create_good()
    # goods.delete_good()
    # inv.set_inv()
    inv.sell()
    # inv.reback()
